package asorm.db
{
	import flash.data.SQLResult;
	import mx.collections.ArrayCollection;
	import asorm.db.event.LocalDatabaseEvent;

	public class LocalDatabaseTable
	{
		public function LocalDatabaseTable(ldb: LocalDatabase, name: String, createSQL: String, propertyMapping: Object) {
			_ldb = ldb;
			_name = name;
			_createSQL = createSQL;
			_propertyMapping = propertyMapping;
		}
		
		public function get database(): LocalDatabase {
			return _ldb;
		}
		
		[Bindable]
		public function get name(): String {
			return _name;
		}
		
		public function set createSQL(sql: String): void {
			_createSQL = sql;
		}
		
		public function set propertyMapping(newPropertyMapping: Object): void {
			_propertyMapping = newPropertyMapping;
		}
		
		public function get propertyMapping(): Object {
			return _propertyMapping;
		}
		
		[Bindable]
		public function get lastResult(): Array {
			return _lastResult;
		}
		
		public function drop(): void {
			executeSQL("DROP TABLE IF EXISTS " + this.name);
		}
		
		public final function create(): void {
			this.executeSQL(_createSQL);
		}
		
		public function executeSQL(sql: String, resulthandler: Function=null): void {
			_ldb.addEventListener(LocalDatabaseEvent.DATABASE_SQL_EXECUTED, resulthandler!=null?resulthandler:handleSQLExecutedEvent);
			database.executeSQL(sql);
		}
		
		public function detachResultHandler(resulthandler: Function): void {
			if (resulthandler != null) {
				_ldb.removeEventListener(LocalDatabaseEvent.DATABASE_SQL_EXECUTED, resulthandler); 
			}
		}
		
		function handleSQLExecutedEvent(event:LocalDatabaseEvent) {
			switch (event.queryType) {
				case LocalDatabaseEvent.QUERYTYPE_SELECT:
					handleSelectResult(event.result);
					break;
				case LocalDatabaseEvent.QUERYTYPE_CREATE_TABLE:
					handleCreateTableResult();
					break;
				case LocalDatabaseEvent.QUERYTYPE_DROP:
					handleDropResult();
					break;
				default:
					break;	
			}
			_ldb.removeEventListener(LocalDatabaseEvent.DATABASE_SQL_EXECUTED, handleSQLExecutedEvent); 
		}

		function handleDropResult(): void {
			trace("Table '" + this.name + " succesfully dropped");
		}
		
		function handleCreateTableResult(): void {
			trace("Table '" + this.name + " succesfully created");
		}
		
		
		function handleSelectResult(result:SQLResult): void {
			trace("'load all' query succesfully executed");
			var numRows: int = result==null||result.data==null ? 0 : result.data.length;
			_lastResult = result.data as Array;
		}

		private var _ldb: LocalDatabase;
		private var _name: String;
		private var _createSQL: String;
		private var _propertyMapping: Object;
		private var _lastResult: Array;
					
	}
}